package com.schoolgard.action.system;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.schoolegard.services.OrganizationService;
import com.schoolegard.services.RoleService;
import com.schoolegard.services.UsersService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.Organization;
import com.schoolgard.entitybean.Role;
import com.schoolgard.entitybean.SelectItem;
import com.schoolgard.entitybean.TreeDataModel;
import com.schoolgard.entitybean.Users;
import com.schoolgard.entitybean.UsersHelp;
import com.supersystem.utils.JSONUtils;
import com.supersystem.utils.Md5Utils;

public class UserAction extends BaseAction{
    
	private static Logger logger = Logger.getLogger(UserAction.class);
	private static final long serialVersionUID = 201112052117L;
	
	
	private UsersService usersService;
	private RoleService roleService;
	private OrganizationService organizationService;
	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}


	private UsersHelp user;
	public UsersHelp getUser() {
		return user;
	}
	public void setUser(UsersHelp user) {
		this.user = user;
	}
	public void findAllUser()
	{
		 String startStr = request.getParameter("start"); //grid传过来的当前数据条数
		 String limitStr = request.getParameter("limit"); //每页显示的数据数
		 
		 int start = Integer.parseInt(startStr);
	     int limit = Integer.parseInt(limitStr);
	     if (limit == 0) {
	    	 limit = Integer.MAX_VALUE;
	     }
	     int end = start + limit;  //当前页需要显示的数据 start--> end
		Users user = null;
		List<Users> users = usersService.findAllUser();
		List<UsersHelp> usHelp = this.packegUser(users);
		int total = users.size();
		if(end > total)end = total;
		
		GridDataModel<UsersHelp> page = new GridDataModel<UsersHelp>();
		page.setPage(start/limit + 1);
		page.setRows(usHelp);
		page.setTotal(total);
		String jsonStr = JSONObject.fromObject(page).toString();
		writeToResponse(jsonStr);
	}
	
	private List<UsersHelp> packegUser(List<Users> users)
	{
		List<UsersHelp> usersHelp = new ArrayList<UsersHelp>();
		UsersHelp uhelp = null;
		for(int i=0 ; i<users.size() ;i++){
			uhelp = new UsersHelp();
			Users us = users.get(i);
			uhelp.setGuid(us.getGuid());
			uhelp.setId(us.getId());
			uhelp.setLoginid(us.getLoginid());
			uhelp.setMail(us.getMail());
			uhelp.setMobile(us.getMobile());
			uhelp.setName(us.getName());
			uhelp.setOrganizationId(us.getOrganization().getId());
			uhelp.setOrganizationName(us.getOrganization().getName());
			uhelp.setPriority(us.getPriority());
			uhelp.setStatus(us.getStatus());
			usersHelp.add(uhelp);
		}
		
		return usersHelp;
	}
	
	public void saveUser()
	{  //此处不保存权限内容，权限内容在授权里面弄
		Long userId = user.getId();
		Users us = null;
		if(userId == null || userId == 0){ //新增
			us = new Users();
		}else{//修改
			us = usersService.findById(userId);
		}
		
		us.setLoginid(user.getLoginid());
		us.setMail(user.getMail());
		us.setMobile(user.getMobile());
		us.setName(user.getName());
		us.setPassword(Md5Utils.getMD5String(user.getPassword()));
		us.setStatus(user.getStatus());
		us.setOrganization(organizationService.findById(user.getOrganizationId()));
		usersService.saveOrUpdate(us);
	}
	
	public void savePassword()
	{
		String password = request.getParameter("passwordConfirm");
		String userId = request.getParameter("cp_user_id");
		if(StringUtils.isBlank(userId)) {
			writeToResponse("0"); 
			return;
		}
		Users user = usersService.findById(Long.valueOf(userId));
		user.setPassword(Md5Utils.getMD5String(password));
		usersService.saveOrUpdate(user);
		writeToResponse("1");
	}
	
	public void deleteUser()
	{
		String userId = request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			writeToResponse("0");
			return ;
		}
		Users user = usersService.findById(Long.valueOf(userId));
		usersService.delete(user);
		writeToResponse("1");
	}
	
	public void queryOrgList()
	{
		List<TreeDataModel> orgTrees =  queryOrgTree("0");
		writeToResponse(com.supersystem.utils.JSONUtils.toJSONString(orgTrees));
	}
	
	public List<TreeDataModel> queryOrgTree(String parentId){
		if(StringUtils.isBlank(parentId)){
			parentId = "0";  //ROOT
		}
		List<TreeDataModel> treeNodes = new ArrayList<TreeDataModel>();
		List<Organization> organizations = organizationService.findByParentId(Long.valueOf(parentId));
		for (Organization organization : organizations) {
			TreeDataModel orgTree = new TreeDataModel();
			orgTree.setId(Long.toString(organization.getId()));
			orgTree.setText(organization.getName());
			List<TreeDataModel> children = queryOrgTree(organization.getId().toString());
			
			if(children == null){
				orgTree.setChildren(null);
			}else{
				orgTree.setChildren(children);
			}
			treeNodes.add(orgTree);
		}
		return treeNodes;
	}
	
	public void findAuthority()
	{
		List<Role> roles = roleService.findAllRole(); 
		List<SelectItem> items = new ArrayList<SelectItem>();
		SelectItem item = null;
		for(int i=0 ; i<roles.size() ; i++){
			items.add(new SelectItem(roles.get(i).getName(),roles.get(i).getId()));
		}
		writeToResponse(JSONUtils.toJSONString(items));
	}
	
	
	public void findAuthoryByUserId()
	{
		String userId = request.getParameter("userId");
		if(StringUtils.isNotBlank(userId)){
			String roleIds = usersService.findRolesByUserId(Long.valueOf(userId));
			writeToResponse(roleIds);
		}else{
			writeToResponse("0");
		}
	}
	
	public void saveAuthority()
	{
		String authorityValue = request.getParameter("authorityValue");
		String userIdAuthority = request.getParameter("userIdAuthority");
		if(StringUtils.isNotBlank(userIdAuthority)){
			usersService.saveAuthority(Long.valueOf(userIdAuthority),authorityValue);
			writeToResponse("1");
			return ;
		}else{
			writeToResponse("0");
			return ;
		}
	}
	
}
